package com.example.spider.config;

import com.example.spider.event.listener.SpiderUrlsManager;
import com.example.spider.spider.Spider;
import com.example.spider.starter.SpiderStarter;
import com.example.spider.task.SpiderManager;
import com.example.spider.task.SpiderResultHandlerManager;
import com.example.spider.task.VirtualThreadSpiderManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJava;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.system.JavaVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.util.unit.DataSize;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class SpiderConfiguration {

    @Bean
    @ConditionalOnProperty(value = "spider.limit.downloadSpeed", havingValue = "0", matchIfMissing = true)
    public SpiderManager spiderManager(Spider spider, SpiderResultHandlerManager resultHandlerManager,
                                       SpiderUrlsManager spiderUrlsManager, @Nullable List<SpiderStarter> spiderStarters,
                                       @Qualifier(ThreadPoolConfiguration.SPIDER) ThreadPoolExecutor spiderThreadPool) {
        return new SpiderManager(spider, resultHandlerManager, spiderUrlsManager, spiderStarters, spiderThreadPool);
    }

    @Bean
    @ConditionalOnProperty(value = "spider.limit.downloadSpeed")
    @ConditionalOnJava(JavaVersion.TWENTY)
    public SpiderManager virtualSpiderManager(Spider spider, SpiderResultHandlerManager resultHandlerManager,
                                              SpiderUrlsManager spiderUrlsManager, @Nullable List<SpiderStarter> spiderStarters,
                                              @Value("${spider.limit.downloadSpeed}") DataSize dataSize
    ) {
        return new VirtualThreadSpiderManager(spider, resultHandlerManager, spiderUrlsManager, spiderStarters, dataSize);
    }

}
